package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareDao;
import com.atguigu.gulimall.ware.entity.WareEntity;
import com.atguigu.gulimall.ware.feign.MemberFeignService;
import com.atguigu.gulimall.ware.service.WareService;
import com.atguigu.gulimall.ware.vo.FareResponseVo;
import com.atguigu.gulimall.ware.vo.MemberAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;


@Service("wareService")
public class WareServiceImpl extends ServiceImpl<WareDao, WareEntity> implements WareService {

    @Resource
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("id", key).or().like("name", key);
        }
        IPage<WareEntity> page = this.page(
                new Query<WareEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 根据用户收货地址计算运费
     * @param addrId
     * @return
     */
    @Override
    public FareResponseVo getFare(Long addrId) {
        FareResponseVo fareResponseVo = new FareResponseVo();
        R r = memberFeignService.addrInfo(addrId);
        MemberAddressVo data = r.getData("userAddress", new TypeReference<MemberAddressVo>() {
        });
        fareResponseVo.setMemberAddressVo(data);
        if (data != null) {
            BigDecimal fare = new BigDecimal(data.getPhone().substring(data.getPhone().length() - 1));
            fareResponseVo.setFare(fare);
        }
        return fareResponseVo;
    }

}